import api from '../../../fetch/api';
import moment from 'moment';
import { getTreeChildNodes } from '../../../assets/js/help.js';

export default {
	data() {
		return {
			bigImgPath: '',
			curRow: {
				carNo: '',
				topBillCode: '',
				parkUUID: '',
				comment: ''
			},
			bindingCarCodeList: [],
			inventorySelectParkingLot: {
				parkName: '',
				parkId: ''
			},
			invertoryType: 'time',
			inventoryUploadFileData: {
				fileName: '',
				file: '',
				clearTime: ''
			},
			clearByTime_time: '',
			clearByTimeTotal: '',
			clearByTimeComment: '',
			batchComment: '',
			uploadFileCheckData: null,
			additionRecord: 0,
			uploadFileComment: '',
			parkingLotList: [] //单选停车场列表
		};
	},
	mounted() {
		$(document).on('change', '#inventoryUploadFile', e => {
			this.inventoryUploadFileData.fileName = $('#inventoryUploadFile')[0].files[0].name;
			this.inventoryUploadFileData.file = $('#inventoryUploadFile')[0].files[0];
		});
	},
	methods: {
		openInventoryModal() {
			this.invertoryType = 'time';
			this.inventorySelectParkingLot = {
				parkName: '',
				parkId: ''
			};
			const now = this.getNowDateTime();
			this.clearByTime_time = now;
			this.inventoryUploadFileData = {
				fileName: '',
				file: '',
				clearTime: now
			};
			this.clearByTimeTotal = '';
			this.clearByTimeComment = '';
			this.uploadFileCheckData = null;
			this.additionRecord = 0;
			this.uploadFileComment = '';
			this.initParkTree();
			this.dialogSetting.isSmartInventoryVisiable = true;
		},
		getNowDateTime() {
			const now = new Date();
			return `${now.getFullYear()}-${now.getMonth() +
				1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
		},
		openBulkInventoryModal() {
			if (!this.selectionList.length) {
				this.showToast('请先选择记录', 0);
				return;
			}

			(this.batchComment = ''), (this.dialogSetting.batchSmartInventoryVisiable = true);
		},
		bulkInventory() {
			if (!this.batchComment) {
				this.showToast('请备注盘点原因', 0);
				return;
			}

			const topBillCodeList = this.selectionList.map(item => item.topBillCode);
			API.fetchPost('/park/presentCar/clearByTopBillCodeList', null, {
				params: {
					topBillCodeList: topBillCodeList.join(','),
					operatorName: this.userLoginId,
					comment: this.batchComment
				}
			}).then(res => {
				this.showToast('批量盘点成功!', 1, 2000);
				this.selectionList = [];
				this.dialogSetting.batchSmartInventoryVisiable = false;
				this.getList();
			});
		},
		// 获取停车场列表数据
		initParkTree() {
			let _self = this;
			API.fetchGet('/parkingBaseData/getParkingBaseDataTree.do', {}).then(
				res => {
					if (res.data) {
						let nodes = res.data;
						if (nodes.childrenNum && nodes.children) {
							_self.parkingLotList = getTreeChildNodes(nodes.children, '');
						}
					} else {
						_self.parkingLotList = [];
					}
				},
				err => {}
			);
		},
		uploadInventoryFile() {
			$('#inventoryUploadFile').click();
		},
		clearByTimeCheck() {
			if (!this.inventorySelectParkingLot.parkId) {
				this.showToast('未选择任何停车场!', 2, 2000);
				return;
			}

			if (!this.clearByTime_time) {
				this.showToast('请选择日期时间!', 2, 2000);
				return;
			}

			API.fetchPost('/park/presentCar/clearByTimeCheck', null, {
				params: {
					clearTime: this.clearByTime_time,
					parkUUID: this.inventorySelectParkingLot.parkId
				}
			}).then(res => {
				this.clearByTimeTotal = res.data.total;
				this.dialogSetting.isSmartInventoryVisiable = false;
				this.dialogSetting.isSmartInventoryTimeVisiable = true;
			});
		},
		submitClearByTime() {
			API.fetchPost('/park/presentCar/clearByTimeCheck', null, {
				params: {
					clearTime: this.clearByTime_time,
					parkUUID: this.inventorySelectParkingLot.parkId
				}
			}).then(res => {
				this.clearByTimeTotal = res.data.total;
				this.dialogSetting.isSmartInventoryVisiable = false;
				this.dialogSetting.isSmartInventoryTimeVisiable = true;
			});
		},
		submitClearByTime() {
			if (!this.clearByTimeComment) {
				this.showToast('盘点原因不能为空', 2, 2000);
				return;
			}
			API.fetchPost('/park/presentCar/clearByTime', null, {
				params: {
					clearTime: this.clearByTime_time,
					parkUUID: this.inventorySelectParkingLot.parkId,
					comment: this.clearByTimeComment,
					operatorName: this.userLoginId
				}
			}).then(res => {
				this.dialogSetting.isSmartInventoryTimeVisiable = false;
				this.showToast('盘点成功!', 0, 2000);
			});
		},
		uploadInventoryFileToServer() {
			if (!this.inventorySelectParkingLot.parkId) {
				this.showToast('未选择任何停车场!', 2, 2000);
				return;
			}

			if (!this.inventoryUploadFileData.file) {
				this.showToast('未选择任何文件!', 2, 2000);
				return;
			}
			if (!this.inventoryUploadFileData.clearTime) {
				this.showToast('请选择日期时间!', 2, 2000);
				return;
			}

			var formData = new FormData();
			formData.append('autoClearFile', this.inventoryUploadFileData.file);
			API.fetchPost('/park/presentCar/autoClearCarCheck', formData, {
				params: {
					clearTime: this.inventoryUploadFileData.clearTime,
					operatorName: this.userLoginId,
					parkUUID: this.inventorySelectParkingLot.parkId
				}
			}).then(res => {
				this.uploadFileCheckData = res.data;
				this.dialogSetting.isSmartInventoryVisiable = false;
				this.dialogSetting.isSmartInventoryInCarVisiable = true;
			});
		},
		getNoRecord() {
			window.open(
				`${location.origin}/mgr/park/presentCar/autoClearCarExcel?clearCode=${this.uploadFileCheckData.clearCode}`
			);
		},
		downloadTemplate() {
			var self = this;
			$.ajax({
				url: '/mgr/importFlie/createExcelTmp.do',
				dataType: 'json',
				data: {
					fileName: 'auto_clear_car',
					fileType: 'xls'
				},
				type: 'get',
				success: function(result) {
					var r = result;
					if (r.success) {
						if (r && r.success) {
							self.showToast('下载成功', 1);
							window.location.href = encodeURI('/mgr/common/templateDownload.do?fileName=' + r.fileName);
						} else {
							self.showToast('下载失败', 2);
						}
					}
				}
			});
		},
		submitUploadFileInventory() {
			if (!this.uploadFileComment) {
				this.showToast('盘点原因不能为空!', 2, 2000);
				return;
			}
			API.fetchPost('/park/presentCar/autoClearCar', null, {
				params: {
					clearCode: this.uploadFileCheckData.clearCode,
					comment: this.uploadFileComment,
					additionRecord: this.additionRecord,
					operatorName: this.userLoginId
				}
			}).then(res => {
				this.dialogSetting.isSmartInventoryInCarVisiable = false;
				this.showToast('盘点成功!', 0, 2000);
			});
		},
		// 获取进场通道列表
		getEnterChannelList() {
			let self = this;
			API.fetchGet('commonFun/channel/findEnterChannelList.do', {}).then(
				res => {
					let data = res.data ? res.data : {};
					let enterChannelList = [];
					enterChannelList.push({
						name: '全部',
						value: ''
					});
					for (var key in data) {
						let obj = data[key];
						obj.forEach(element => {
							let tmpObj = {
								value: element.entranceName,
								name: element.entranceName
							};
							enterChannelList.push(tmpObj);
						});
					}
					self.searchList[9].value = '';
					self.searchList[9].options = enterChannelList;
				},
				err => {}
			);
		},
		// 查看已绑定的车牌号
		checkBindingCarCode(row, modalName) {
			let self = this;
			self.bindingCarCodeList = [];
			let params = {
				logicCardCode: row.carNo
			};
			API.fetchGet('monthTicketBill/getLogicCardCodeDetail', params).then(
				res => {
					if (res.data) {
						let data = res.data;
						let obj = {
							carCode: data.logicCardCode //车牌
						};
						if (data.openid) {
							//微信
							obj.cardCode = data.nickname; //备注卡号
						} else {
							obj.cardCode = data.cardCode; //备注卡号
						}
						self.bindingCarCodeList.push(obj);
					}
					self.toOpenModal(modalName);
				},
				err => {}
			);
		},
		getList() {
			let params = $.extend({}, this.searchParams, this.otherParams);
			if (!params.parkIds) {
				this.showToast('请先选择停车场!', 0);
				return;
			}
			if (this.searchList[4].value) {
				if (!/^\d+$/.test(this.searchList[4].value)) {
					this.showToast('停车时长只能输入数字!', 0);
					return;
				}
			}
			if (params.hasOwnProperty('plate')) {
				delete params.plate;
				let attribStr = this.searchList[1].value;
				params[attribStr] = this.searchList[1].inputVal;
			}
			if (params) {
				for (let key in params) {
					if (params[key] === '' || params[key] === null) {
						delete params[key];
					}
				}
			}
			this.getItemList(params);
		},
		showBigImgModal(name, path) {
			this.bigImgPath = path;
			this.toOpenImgModal(name, path);
		},
		//获取列表
		getItemList(aparams) {
			let self = this,
				params = {
					page: this.pageNumber,
					rp: this.pageSize
				};
			params = $.extend({}, params, aparams);
			self.tbodysInfo = [];
			api.fetchGet('/park/presentCar/getPresentCar.do', params).then(
				res => {
					let data = res.data,
						list = data.rows;
					self.tbodysInfo = list;
					self.total = data.total;
					if (aparams['areaIds']) {
						//选了区域
						self.theadsInfo[1].initHidden = false;
					} else {
						self.theadsInfo[1].initHidden = true;
					}
					self.isResetTable = false;
					self.$nextTick(() => {
						self.isResetTable = true;
					});
				},
				err => {}
			);
		},
		initCorrectData() {
			let _this = this;
			_this.carType = '';
			_this.keyBoard.Val = '';
		},
		flipItem(operate) {
			//详情翻页按钮
			var _this = this;
			_this.initCorrectData();
			switch (operate) {
				case 'next':
					if (_this.nextDisable) {
						// _this.showToast("当前已经是最后一个车牌", 2, 2000);
						return;
					}
					_this.prevDisable = false;
					_this.currentIndex++;

					if (_this.currentIndex == _this.tbodysInfo.length - 1) {
						_this.nextDisable = true;
					}
					break;
				case 'prev':
					// 判断是否要执行_this.currentIndex--;
					if (_this.prevDisable) {
						// _this.showToast("当前已经是第一个车牌", 2, 2000);
						return;
					}
					//点击上一页的时候下一页默认可使用
					_this.nextDisable = false;
					_this.currentIndex--;

					if (_this.currentIndex == 0) {
						_this.prevDisable = true;
					}
					break;
				default:
					break;
			}
			_this.correctModalData = _this.tbodysInfo[_this.currentIndex];
		},
		// 刷新剩余车位数
		refresh() {
			let _this = this;
			let params = {
				parkCode: _this.residueData.parkCode
			};
			api.fetchPost('/park/presentCar/flushRemainTemporaryParkingLotNum.do', params).then(
				response => {
					if (response.resultCode == 0) {
						_this.residueData.screenNum = response.data.screenRemainTemporaryParkingLotNum;
						_this.showToast('操作成功', 1, 2000);
					} else {
						_this.showToast(response.message, 2, 2000);
					}
				},
				err => {}
			);
		},
		//设置剩余车位
		setResidueModal_open() {
			let _this = this;
			_this
				.getParkList()
				.then(function() {
					_this.getRemainCar();
				})
				.catch(function(res) {
					console.log(res);
				});
			_this.toOpenModal('residueModal');
		},
		//设置显示屏数量
		setRemianNum() {
			let _this = this;
			if (_this.residueData.screenNum_set == '') {
				_this.showToast('临时车位数不能为空', 2, 2000);
				return;
			}
			if (
				parseInt(_this.residueData.totalCW) < parseInt(_this.residueData.screenNum_set) ||
				parseInt(_this.residueData.screenNum_set) <= 0
			) {
				_this.showToast('请输入大于0且小于等于总临时车位数的数值', 2, 2000);
				return;
			}
			let params = {
				parkCode: _this.residueData.parkCode,
				screenRemainTemporaryParkingLotNum: _this.residueData.screenNum_set
			};
			api.fetchPost('/park/presentCar/setRemainTemporaryParkingLotNum.do', params).then(
				response => {
					if (response.resultCode == 0) {
						_this.residueData.screenNum = response.data.screenRemainTemporaryParkingLotNum;
						_this.showToast('操作成功', 1, 2000);
					} else {
						_this.showToast(response.message, 2, 2000);
					}
				},
				err => {}
			);
		},
		// 获取剩余车位数
		getRemainCar() {
			let _this = this;
			let timeT = moment().format('YYYY-MM-DD HH:mm:ss');
			let timeF = moment()
				.subtract(_this.residueData.gap, 'hours')
				.format('YYYY-MM-DD HH:mm:ss');
			let params = {
				parkId: _this.residueData.parkId,
				parkCode: _this.residueData.parkCode,
				tempCarports: _this.residueData.totalCW,
				approchTimeFrom: timeF,
				approchTimeTo: timeT
			};
			api.fetchPost('/park/presentCar/countPresentCarTimeSlot.do', params).then(
				response => {
					if (response.resultCode == 0) {
						_this.residueData.presentCarTimeSlot = response.data.presentCarTimeSlot;
						_this.residueData.remainTempCarports = response.data.remainTempCarports;
					} else {
						_this.showToast(response.message, 2, 2000);
					}
				},
				err => {}
			);
		},
		// 获取设置剩余车位停车场的列表
		getParkList() {
			let _this = this;
			return new Promise(function(resolve, reject) {
				let params = {
					page: 1,
					rp: 1000
				};
				api.fetchGet('/parkingBaseData/list.do', params).then(
					res => {
						_this.parkList = res.data.rows;
						_this.residueData.parkId = res.data.rows[0].id ? res.data.rows[0].id : 0;
						_this.residueData.totalCW = res.data.rows[0].tempCarports ? res.data.rows[0].tempCarports : 0;
						_this.id_tempCarports =
							res.data.rows[0].parkCode + '/' + res.data.rows[0].tempCarports + '/' + res.data.rows[0].id;
						resolve();
					},
					err => {
						reject();
					}
				);
			});
		},
		// 校正车牌
		correctModal_open(index) {
			let _this = this;
			_this.correctModalData = _this.tbodysInfo[index];
			_this.currentIndex = index;
			_this.currentIndex == 0 ? (_this.prevDisable = true) : (_this.prevDisable = false);
			_this.currentIndex == _this.tbodysInfo.length - 1
				? (_this.nextDisable = true)
				: (_this.nextDisable = false);
			_this.initCorrectData();
			_this.toOpenModal('correctModal');
		},
		// 打开车辆盘离modal
		toOpenSumCarLeaveModal(row) {
			this.curRow.carNo = row.carNo;
			this.curRow.topBillCode = row.topBillCode;
			this.curRow.parkUUID = row.parkUUID;
			this.curRow.comment = '';
			this.toOpenModal('sumCarLeaveModal');
		},
		//车辆盘离
		checkLeave() {
			let _this = this;
			if (_this.curRow.comment && _this.curRow.comment.length > 30) {
				_this.isTooMuch = true;
				return;
			}
			_this.isTooMuch = false;
			let params = {
				topBillCode: _this.curRow.topBillCode,
				parkUUID: _this.curRow.parkUUID,
				comment: _this.curRow.comment
			};
			api.fetchPost('/park/presentCar/check.do', params).then(
				res => {
					if (res.resultCode == 0) {
						_this.showToast('操作成功', 1, 2000);
						_this.getList();
						_this.closed('sumCarLeaveModal');
					} else {
						_this.showToast(res.message, 2, 2000);
					}
				},
				err => {}
			);
		},
		correct_save(type) {
			let _this = this;
			let params = {
				topBillCode: _this.correctModalData.topBillCode,
				newCarCode: $('#newCarCode').val(),
				recordType: type ? type : 1
			};
			api.fetchPost('/park/presentCar/adjustCarNo.do', params).then(
				response => {
					if (response.resultCode == 0) {
						// icon: 0:普通提示 1：正确的提示 2： 错误提示
						// time: 不填默认1000ms
						_this.showToast('校正成功', 1, 2000);
						_this.flipItem('next');
						_this.getList();
					} else {
						_this.showToast(response.message, 2, 2000);
						return;
					}
				},
				err => {}
			);
		},
		exportData() {
			let self = this;
			let theadsArr = [];
			for (let i = 0; i < self.theadsInfo.length; i++) {
				if (self.theadsInfo[i].checked) {
					theadsArr.push(self.theadsInfo[i].prop);
				}
			}
			let params = {
				meterList: theadsArr.join(',')
			};
			params = $.extend({}, params, this.searchParams, this.otherParams);
			if (params.hasOwnProperty('plate')) {
				delete params.plate;
				let attribStr = this.searchList[1].value;
				params[attribStr] = this.searchList[1].inputVal;
			}
			for (let key in params) {
				if (params.hasOwnProperty(key)) {
					if (params[key] !== 0 && !params[key]) {
						delete params[key];
					}
				}
			}
			self.showDialog('确认导出该报表?', '', function() {
				self.toExportAsync('park/presentCar/exportPresentCar.do', params);
			});
		},
		// 处理访问不了的图片
		handleImg(e, rowObj) {
			if (e.target.className == 'carNoImageUrl') {
				//小图
				rowObj.carNoImageUrl = null;
			} else if (e.target.className == 'carImageUrl') {
				//大图
				rowObj.carImageUrl = null;
			}
		}
	}
};
